<?php
if (!function_exists('getClientIP')) {
    /**
     * @return mixed|string
     */
    function getClientIP()
    {
        $ip = '';

        // 判断是否存在 REMOTE_ADDR
        if (!empty($_SERVER['REMOTE_ADDR'])) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }

        // 判断是否存在 HTTP_X_FORWARDED_FOR
        if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            // 使用逗号分隔的 IP 列表，获取第一个 IP 地址
            $ip_list = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
            $ip_list = array_map('trim', $ip_list); // 移除每个 IP 前后的空格
            $forwarded_ip = reset($ip_list); // 获取第一个 IP 地址
            // 如果第一个 IP 地址不是内网地址，或者为空，则将其作为客户端 IP
            if (!empty($forwarded_ip) && !filter_var($forwarded_ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
                $ip = $forwarded_ip;
            }
        }

        // 返回获取到的 IP 地址
        return $ip;
    }
}

if (!function_exists('session')) {
    /**
     * @param $key
     * @param $value
     * @return mixed
     */
    function session($key,$value=null){
        if($value !== null){
            $_SESSION[$key] = $value;
            return $value;
        }else{
            return $_SESSION[$key];
        }
    }
}

if (!function_exists('validate')) {
    /**
     * 验证参数
     * @param $data
     * @param $rules
     * @return bool|string
     */
    function validate($data,$rules){
        foreach ($rules as $key=>$value){
            $name_array = explode('|',$key);
            foreach (explode('|',$value) as $rule){
                switch ($rule){
                    case 'require':
                        if(!isset($data[$name_array[0]]) || $data[$name_array[0]]==''){
                            return ($name_array[1]??$name_array[0])."不能为空！";
                        }
                }
            }
        }
        return true;
    }
}


if (!function_exists('parse_sql')) {
    /**
     * 分割sql语句
     * @param  string $content sql内容
     * @param  bool $limit  如果为1，则只返回一条sql语句，默认返回所有
     * @param  array $prefix 替换前缀
     * @return array|string 除去注释之后的sql语句数组或一条语句
     */
    function parse_sql($sql = '', $limit = 0, $prefix = []) {
        // 被替换的前缀
        $from = '';
        // 要替换的前缀
        $to = '';

        // 替换表前缀
        if (!empty($prefix)) {
            $to   = current($prefix);
            $from = current(array_flip($prefix));
        }

        if ($sql != '') {
            // 纯sql内容
            $pure_sql = [];

            // 多行注释标记
            $comment = false;

            // 按行分割，兼容多个平台
            $sql = str_replace(["\r\n", "\r"], "\n", $sql);
            $sql = explode("\n", trim($sql));

            // 循环处理每一行
            foreach ($sql as $key => $line) {
                // 跳过空行
                if ($line == '') {
                    continue;
                }

                // 跳过以#或者--开头的单行注释
                if (preg_match("/^(#|--)/", $line)) {
                    continue;
                }

                // 跳过以/**/包裹起来的单行注释
                if (preg_match("/^\/\*(.*?)\*\//", $line)) {
                    continue;
                }

                // 多行注释开始
                if (substr($line, 0, 2) == '/*') {
                    $comment = true;
                    continue;
                }

                // 多行注释结束
                if (substr($line, -2) == '*/') {
                    $comment = false;
                    continue;
                }

                // 多行注释没有结束，继续跳过
                if ($comment) {
                    continue;
                }

                // 替换表前缀
                if ($from != '') {
                    $line = str_replace('`'.$from, '`'.$to, $line);
                }
                if ($line == 'BEGIN;' || $line =='COMMIT;') {
                    continue;
                }
                // sql语句
                array_push($pure_sql, $line);
            }

            // 只返回一条语句
            if ($limit == 1) {
                return implode("",$pure_sql);
            }

            // 以数组形式返回sql语句
            $pure_sql = implode("\n",$pure_sql);
            $pure_sql = explode(";\n", $pure_sql);
            return $pure_sql;
        } else {
            return $limit == 1 ? '' : [];
        }
    }
}

/**
 * @return string
 */
function getSalt(){
    $cgaracrers = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $salt = '';
    for ($i = 0; $i < 6; $i++) {
        $salt .= $cgaracrers[rand(0, strlen($cgaracrers) - 1)];
    }
    return $salt;
}

/**
 * @param $password
 * @param $salt
 * @return string
 */
function getPassword($password,$salt=null){
    if(!$salt){
        $salt = getSalt();
    }
    $encrypted_data1 = md5($password);
    $encrypted_data2 = hash("sha512", $encrypted_data1 . $salt);
    $encrypted_data = hash("sha512", $encrypted_data2);
    return $encrypted_data;
}

function jsonReturn($code,$msg = '', string $url = null, $data = [], int $wait = 3, array $header = []){
    $header[] = 'Content-Type: application/json';
    foreach ($header as $value) {
        header($value);
    }
    $result = [
        'code' => $code,
        'msg' => $msg,
        'url' => $url,
        'wait' => $wait,
    ];
    $result = array_merge($result,$data);
    exit(json_encode($result));
}

if (!function_exists('success')) {
    /**
     * @param string $msg
     * @param string|null $url
     * @param string $data
     * @param int $wait
     * @param array $header
     * @return void
     */
    function success($msg = '', string $url = null, $data = [], int $wait = 3, array $header = [])
    {
        if (empty($_POST)) {
            $result = [
                'title'=>'Success',
                'msg'=>$msg,
                'url'=>$url,
                'wait'=>$wait,
                'header'=>$header,
            ];
            $result = array_merge($result,$data);
            view('message',$result,'system');
            exit();
        } else {
            jsonReturn(1,$msg ,  $url , $data, $wait,  $header);
        }
    }
}

if (!function_exists('error')) {
    /**
     * @param string $msg
     * @param string|null $url
     * @param string $data
     * @param int $wait
     * @param array $header
     * @return void
     */
    function error($msg = '', string $url = null, $data = [], int $wait = 3, array $header = [])
    {
        if (empty($_POST)) {
            $result = [
                'title'=>'Error',
                'msg'=>$msg,
                'url'=>$url,
                'wait'=>$wait,
                'header'=>$header,
            ];
            $result = array_merge($result,$data);
            view('message',$result,'system');
            exit();
        } else {
            jsonReturn(0,$msg ,  $url , $data, $wait,  $header);
        }
    }
}

if (!function_exists('view')) {
    /**
     * @param $template
     * @param $data
     * @param $model
     * @param $type
     * @return void
     */
    function view($template,$data=[],$model='index',$type='php')
    {
        $template_file = APP_PATH.'/view/'.$model.'/'.$template.'.'.$type;
        if(file_exists($template_file)){
            require $template_file;
        }else{
            error('模版不存在！');
        }
    }
}

/**
 * @param $model
 * @param $controller
 * @param $action
 * @return array
 */
function getMca($model,$controller,$action){
    return [
        'model'      => $_GET['m']??$model,
        'controller' => $_GET['c']??$controller,
        'action'     => $_GET['a']??$action,
    ];
}

/**
 * @param $model
 * @param $controller
 * @param $action
 * @param $params
 * @return string
 */
function getUrl($model='',$controller='',$action='',$params=[]){
    if(empty($model))           $model = 'index';
    if(empty($controller))      $controller = 'index';
    if(empty($action))          $action = 'index';
    if($model != 'index')       $params['m'] = $model;
    if($controller != 'index')  $params['c'] = $controller;
    if($action != 'index')      $params['a'] = $action;
    return '/?'.http_build_query($params);
}